import os
import time

from PIL import Image
from fdfs_client.client import Fdfs_client, Storage_server, ResponseError, DataError

from hash.hash import CalcSha1
from xjlibrary.database_moudel.base_sql import insert
from xjlibrary.database_moudel.mysql_client import mysql
from xjlibrary.tools.base_utils import SUFFIX
from xjlibrary.tools.filename_giveup import is_img, get_file_name, get_file_ext_name, gettime
from xjlibrary.tools.movieformatconversion import getListFiles


def store_serv_hook(store_serv: Storage_server) -> Storage_server:
    store_serv.ip_addr = b'xujiang5.xicp.io'
    return store_serv

trackers = {"host_tuple": ("xujiang5.xicp.io",), "port": 22122, "timeout": 360}
client = Fdfs_client(trackers)
client.register_store_serv_hook(store_serv_hook)



def appromix(size, base=0):
    '''Conver bytes stream size to human-readable format.
    Keyword arguments:
    size: int, bytes stream size
    base: int, suffix index
    Return: string
    '''
    multiples = 1024
    if size < 0:
        raise ValueError('[-] Error: number must be non-negative.')
    if size < multiples:
        return '{0:d}{1}'.format(size, SUFFIX[base])
    for suffix in SUFFIX[base:]:
        if size < multiples:
            return '{0:.2f}{1}'.format(size, suffix)
        size = size / float(multiples)
    raise ValueError('[-] Error: number too big.')


def getfileinfo(filename):
    fileinfo = {}
    # 获取文件名
    fileinfo["LocalFileName"] = get_file_name(filename)
    if is_img(get_file_ext_name(filename)):
        img = Image.open(filename)
        wide, high = img.size
        fileinfo["Widehigh"] = str(wide)+","+str(high)
    else:
        fileinfo["Widehigh"] = ''
    # statinfo = os.stat(filename)
    # print(statinfo)
    # ret = get_exif_data(filename)
    fileinfo['TimeConsume'] = gettime(filename)
    # 获取文件hash
    hash = CalcSha1(filename)
    fileinfo['hash'] = hash
    try:
        file_size = os.stat(filename).st_size
        # meta_buffer can be null.
        meta_dict = {
            'ext_name': get_file_ext_name(filename),
            'file_size': str(file_size) + 'B',
            'hash': str(hash)
        }
        print(meta_dict)

        t1 = time.time()
        print(t1)
        ret_dict = client.upload_by_filename(filename, meta_dict)
        print(ret_dict)
        t2 = time.time()
        savedate(fileinfo, ret_dict)
        for key in ret_dict:
            print('[+] %s : %s' % (key, ret_dict[key]))

        print('[+] time consume: %fs' % (t2 - t1))
    except (ConnectionError, ResponseError, DataError) as e:
        print(e)

def savedate(fileinfo, ret_dict):
    switcher = {
        "Group name": "GroupName",
        "Remote file_id": "RemoteFileId",
        "Status": "Status",
        "Uploaded size": "UploadedSize",
        "Storage IP": "StorageIp",

    }
    for key in ret_dict:
        if key == "Local file name":
            continue
        if isinstance(ret_dict[key], bytes):
            ret_dict[key] = ret_dict[key].decode()
        fileinfo[switcher[key]] = ret_dict[key]
    fileinfo['FetchTime'] = str(time.time())
    print(fileinfo)
    sql = insert('fdfsfile', fileinfo)
    mysql.execute(sql)
    mysql.commit()



def savefile():
    ret = getListFiles("C:/Users/XD/Pictures/所有视频/")
    for each in ret:
        getfileinfo(each)
        if os.path.exists(each):
            # 删除文件，可使用以下两种方法。
            os.remove(each)

savefile()
mysql.commit()
